package be.jabapage.util;

import java.awt.Dimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

public class PropertiesSingleton {

	private static Logger logger = Logger.getRootLogger();
	private static PropertiesSingleton singleton = null;
	private static Locale DEFAULT_LOCALE = new Locale ("nl","BE");
	
	private Locale locale = null;
	private ResourceBundle bundle = null;
	private Properties guiProperties = null;
	
	private PropertiesSingleton() throws IOException {
		this(DEFAULT_LOCALE);
	}
	private PropertiesSingleton(Locale locale) throws IOException{
		logger.debug("creating propertysingleton for locale " + locale);
		this.locale = locale;
		bundle = ResourceBundle.getBundle("labels", locale);
		loadDefaultDimension();
	}
	private void loadDefaultDimension() throws IOException {
		String path = System.getProperty("user.dir");
		File propFile = new File(path + "/properties/gui_1024_800.properties");
		logger.debug("path to property file = " + propFile.getAbsolutePath());
		guiProperties = new Properties();
//		guiProperties.load(new FileReader(propFile));
	}
	
	public static PropertiesSingleton getInstance() {
		try {
			logger.debug("quering propertiessingleton instance");
			if (singleton == null)
				singleton = new PropertiesSingleton();
			return singleton;
		} catch (IOException e ) {
			logger.error("Error initiating the PropertiesSingleton",e);
			throw new RuntimeException("An Error occured");
		}
	}
	
	/**
	 * @return the locale
	 */
	public Locale getLocale() {
		return locale;
	}

	/**
	 * @param locale the locale to set
	 */
	public void setLocale(Locale locale) {
		logger.debug("update locale to " + locale);
		this.locale = locale;
		bundle = ResourceBundle.getBundle("labels", locale);
	}
	
	public void setDimension(Dimension dim) {
//		try {
			String path = System.getProperty("user.dir");
			String width = Double.toString(dim.getWidth()).split("[.]")[0];
			String height= Double.toString(dim.getHeight()).split("[.]")[0];
			File propFile = new File(path + "/properties/gui_" + width + "_" + height +".properties");
			logger.debug("path to property file = " + propFile.getAbsolutePath());
			guiProperties = new Properties();
//			guiProperties.load(new FileReader(propFile));
//		} catch (IOException e) {
//			logger.error("dimension " + dim + " not found");
//			try {
//				loadDefaultDimension();
//			} catch (IOException ex) {
//				//do nothing
//				logger.error("load of the default dimension failed");
//			}
//		}
	}
	
	public String getString(String key) {
		return bundle.getString(key);
	}
	
	
	public String getGUIProperty(String key) {
		return guiProperties.getProperty(key);
	}
}
